#include "../../source/server.hpp"
#include <string>
#include <vector>

void HandleClose(Channel *channel)
{
    DBG_LOG("close fd: %d", channel->Fd());
    channel->Remove(); // 移除监控
    delete channel;
    channel = nullptr;
}
void HandleRead(Channel *channel)
{
    int fd = channel->Fd();
    char buf[1024] = {0};
    int ret = recv(fd, buf, 1023, 0);
    if (ret <= 0)
    {
        return HandleClose(channel);
    }
    DBG_LOG("%s", buf);
    channel->EnableWrite();
}
void HandleWrite(Channel *channel)
{
    int fd = channel->Fd();
    const char *data = "天气还不错！！";
    int ret = send(fd, data, strlen(data), 0);
    if (ret < 0)
        return HandleClose(channel);
    channel->DisableWrite();
}
void HandleError(Channel *channel)
{
    return HandleClose(channel);
}
void HandleEvent(Channel *channel, EventLoop* loop, uint64_t id)
{
    loop->TimerReflash(id);
}
void Acceptor(EventLoop *loop, Channel *lst_channel)
{
    //fd = socketfd
    int fd = lst_channel->Fd();
    int newfd = accept(fd, NULL, NULL);
    if(newfd < 0)
        return;

    uint64_t timerid = rand() % 10000;
    Channel *channel = new Channel(loop, newfd);
    channel->SetReadCallBack(std::bind(HandleRead, channel));
    channel->SetWriteCallBack(std::bind(HandleWrite, channel));
    channel->SetCloseCallBack(std::bind(HandleClose, channel));
    channel->SetErrorCallBack(std::bind(HandleError, channel));
    channel->SetEventCallBack(std::bind(HandleEvent, channel, loop, timerid));
    channel->EnableRead();
    //非活跃连接件的超时释放操作, 10s后关闭连接
    loop->TimerAdd(timerid, 10, std::bind(HandleClose, channel));
}

int main()
{
    srand(time(NULL));

    EventLoop loop;
    Socket lst_sock;
    lst_sock.CreateServer(8080);
    Channel channel(&loop, lst_sock.Fd());
    channel.SetReadCallBack(std::bind(Acceptor, &loop, &channel));
    channel.EnableRead();
    while(1)
    {
        loop.Start();
    }
    lst_sock.Close();
    return 0;
}